package com.hx.haowumall.haowumallorder.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.hx.common.exception.NoStockException;
import com.hx.common.to.mq.OrderTo;
import com.hx.common.to.mq.SeckillOrderTo;
import com.hx.common.utils.R;
import com.hx.common.vo.MemberRespVo;
import com.hx.haowumall.haowumallorder.constant.OrderConstant;
import com.hx.haowumall.haowumallorder.dao.OrderItemDao;
import com.hx.haowumall.haowumallorder.entity.OrderItemEntity;
import com.hx.haowumall.haowumallorder.entity.PaymentInfoEntity;
import com.hx.haowumall.haowumallorder.enume.OrderStatusEnum;
import com.hx.haowumall.haowumallorder.feign.CartFeignService;
import com.hx.haowumall.haowumallorder.feign.MemberFeignService;
import com.hx.haowumall.haowumallorder.feign.ProductFeignService;
import com.hx.haowumall.haowumallorder.feign.WmsFeignService;
import com.hx.haowumall.haowumallorder.interceptor.LoginUserInterceptor;
import com.hx.haowumall.haowumallorder.service.OrderItemService;
import com.hx.haowumall.haowumallorder.service.PaymentInfoService;
import com.hx.haowumall.haowumallorder.to.OrderCreateTo;
import com.hx.haowumall.haowumallorder.vo.*;
//import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hx.common.utils.PageUtils;
import com.hx.common.utils.Query;

import com.hx.haowumall.haowumallorder.dao.OrderDao;
import com.hx.haowumall.haowumallorder.entity.OrderEntity;
import com.hx.haowumall.haowumallorder.service.OrderService;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> submitThreadLocal = new ThreadLocal<>();

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    WmsFeignService wmsFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    PaymentInfoService paymentInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        //获取前一个的请求
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            //子线程共享之前的请求
            RequestContextHolder.setRequestAttributes(requestAttributes);

            //1、远程查询所有的收获地址列表
            List<MemberAddressVo> address = memberFeignService.getAddress(memberRespVo.getId());
            confirmVo.setAddress(address);
        }, executor);

        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            //2、远程查询购物车所有选中的购物项
            //1）、feign在远程调用之前要调用很多拦截器
            //    feign远程调用丢失请求头的问题  解决：加上feign远程调用的请拦截器同步老的请求头和cookie
            //2）、feign的异步线程，由于非同一个线程运行，ThreadLocal无法在不同线程共享 1）失败
            //     解决在子线程运行前的主线程里设置RequestContextHolder，子线程调用
            //     RequestContextHolder.setRequestAttributes(requestAttributes);

            //子线程共享之前的请求
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> items = cartFeignService.getCurrentUserCartItems();
            confirmVo.setItems(items);
        }, executor).thenRunAsync(()->{
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());

            R hasStock = wmsFeignService.getSkuHasStock(collect);
            List<SkuStockVo> data = hasStock.getData(new TypeReference<List<SkuStockVo>>() {
            });
            if (data != null){
                //skuId->{return skuId.getSkuId();}
                Map<Long, Boolean> stockMap = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                confirmVo.setStocks(stockMap);
            }
        },executor);


        //3、远程查询用户积分信息
        Integer integration = memberRespVo.getIntegration();
        confirmVo.setIntegration(integration);

        //4、其他数据自动计算

        //TODO 5、防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");

        redisTemplate.opsForValue().
                set(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberRespVo.getId(),token,30, TimeUnit.MINUTES);
        confirmVo.setOrderToken(token);

        CompletableFuture.allOf(getAddressFuture,cartFuture).get();

        return confirmVo;
    }


    /**
     * @Transactional(isolation = Isolation.READ_COMMITTED) 设置事务的隔离级别
     * @Transactional(propagation = Propagation.REQUIRED)   设置事务的传播级别
     * 下单详细操作
     * @Transactional:本地事务只能控制自己的回滚，其他服务的回滚无法控制
     * 分布事务最大的原因，网络问题+分布式机器
     * */
//    @GlobalTransactional
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        submitThreadLocal.set(vo);

        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        responseVo.setCode(0);

        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        //1、验证令牌(对比和删除必须为原子操作)
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        String orderToken = vo.getOrderToken();
        //原子验证和删除令牌 返回0失败 1成功
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()), orderToken);
        if (result == 0L){
            //验证失败
            responseVo.setCode(1);
            return responseVo;
        }else {
            //验证成功
            //2、创建订单项设置订单信息
            OrderCreateTo order = createOrder();
            //3、提交订单前的价格和服务器购物车里的价格对比（验价）
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal voPayPrice = vo.getPayPrice();
            if (Math.abs(payAmount.subtract(voPayPrice).doubleValue()) < 0.01){

                //4、对比且锁定成功，保存订单项
                saveOrder(order);

                //5、对比成功，库存锁定,只要有异常就回滚订单数据(订单号，所有订单项（skuId，skuName，num）)
                WareSkuLockVo lockVo = new WareSkuLockVo();
                lockVo.setOrderSn(order.getOrder().getOrderSn());

                List<OrderItemVo> orderItemVos = order.getOrderItems().stream().map(item -> {
                    OrderItemVo itemVo = new OrderItemVo();
                    itemVo.setSkuId(item.getSkuId());
                    itemVo.setCount(item.getSkuQuantity());
                    itemVo.setTitle(item.getSkuName());
                    return itemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(orderItemVos);

                //TODO 远程锁库存
                R r = wmsFeignService.orderLockStock(lockVo);

                if (r.getCode() == 0){
                    //锁定成功

                    //模拟异常
//                    int i = 10/0;
                    responseVo.setOrder(order.getOrder());

                    //TODO 订单成功发送消息给MQ
                    rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder());

                    return responseVo;
                }else {
                    //锁定失败
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
                    //return responseVo;
                }

            }else {
                //对比失败
                responseVo.setCode(2);
                return responseVo;
            }

        }

//        String redisToken = redisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId());
//        if (orderToken !=null && orderToken.equals(redisToken)){
//            //令牌通过
//        }else {
//            //不通过
//        }
//        return responseVo;
    }

    /**
     * 仓库根据orderSn查询订单状态
     * */
    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        OrderEntity order_sn = this.baseMapper.selectOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return order_sn;
    }

    /**
     * 根据orderSn关闭商单
     * */
    @Transactional
    @Override
    public void closeOrder(OrderEntity entity) {
        //查询当前订单的最新状
        OrderEntity orderEntity = this.getById(entity.getId());
//        OrderEntity orderEntity = this.baseMapper.selectOne(new QueryWrapper<OrderEntity>().eq("order_sn", entity.getOrderSn()));
        if (orderEntity.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())){
            //关单
            OrderEntity update = new OrderEntity();
            update.setId(orderEntity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);

            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity,orderTo);
            //发给MQ一个消息
            try {
                //TODO 保证消息一定发出去，给每一个消息做日志记录（给数据库保存每一个消息的详细信息）
                //定期保存扫描数据库，将失败的信息再发一遍
                rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",orderTo);
            } catch (Exception e) {
                //TODO 尝试成功的给MQ发送消息
            }
        }
    }

    @Override
    public PayVo getOrderPayInfo(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity order = this.getOrderByOrderSn(orderSn);
        BigDecimal bigDecimal = order.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(bigDecimal.toString());
        payVo.setOut_trade_no(order.getOrderSn());

        List<OrderItemEntity> order_sn = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity entity = order_sn.get(0);
        payVo.setSubject(entity.getSkuName());
        payVo.setBody(entity.getSkuAttrsVals());
        return payVo;
    }


    /**
     * 查询当前用户的所有订单
     * */
    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {

        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id",memberRespVo.getId()).orderByDesc("id")
        );

        List<OrderEntity> order_sn = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(itemEntities);
            return order;
        }).collect(Collectors.toList());

        page.setRecords(order_sn);
        return new PageUtils(page);
    }

    /**
     * 处理支付宝的支付结果
     * */
//    public Integer temp = null;
    @Override
    public String handlePayResult(PayAsyncVo vo) {
        //1、保存交易流水
        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        infoEntity.setAlipayTradeNo(vo.getTrade_no());
        infoEntity.setOrderSn(vo.getOut_trade_no());
        infoEntity.setCallbackTime(vo.getNotify_time());

        paymentInfoService.save(infoEntity);

        //1、修改订单的状态信息
        if (vo.getTrade_status().equals("TRADE_SUCCESS")||vo.getTrade_status().equals("TRADE_FINISHED")){
            //支付成功状态
            //修改订单页的支付状态
            String outTradeNo = vo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(outTradeNo,OrderStatusEnum.PAYED.getCode());
//            temp = OrderStatusEnum.PAYED.getCode();
        }
        return "success";
    }


    /**
     * 订单信息保存到数据库
     * */
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);

        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);

    }

    /**
     * 创建订单一系列操作：
     * */
    private OrderCreateTo createOrder(){

        OrderCreateTo createTo = new OrderCreateTo();
        //1、生成订单号
        String orderSn = IdWorker.getTimeId();
        //创建订单号
        OrderEntity orderEntity = buildOrder(orderSn);

        //2、获取所有的订单项
        List<OrderItemEntity> itemEntities = buildOrderItems(orderSn);

        //3、计算价格，积分相关信息
        computePrice(orderEntity,itemEntities);
        createTo.setOrder(orderEntity);
        createTo.setOrderItems(itemEntities);

        return createTo;
    }

    /**
     * 创建订单一系列操作：计算价格相关的数据
     * */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {

        //总额
        BigDecimal totalPrice= new BigDecimal("0.0");

        //优惠价
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");

        //积分、成长值
        Integer integrationTotal = 0;
        Integer growthTotal = 0;

        for (OrderItemEntity entity : itemEntities) {
            //优惠价格信息
            coupon = coupon.add(entity.getCouponAmount());
            promotion = promotion.add(entity.getPromotionAmount());
            integration = integration.add(entity.getIntegrationAmount());

            //积分信息和成长值信息
            integrationTotal += entity.getGiftIntegration();
            growthTotal += entity.getGiftGrowth();

            //所有商品项的总额
            totalPrice = totalPrice.add(entity.getRealAmount());
        }

        //1、订单总额(叠加每一个订单项的数据)
        orderEntity.setTotalAmount(totalPrice);
        //2、应付总额
        orderEntity.setPayAmount(totalPrice.add(orderEntity.getFreightAmount()));
        //3、
        //优惠券优惠分解金额
        orderEntity.setCouponAmount(coupon);
        // 商品促销分解金额
        orderEntity.setPromotionAmount(promotion);
        //积分优惠分解金额
        orderEntity.setIntegrationAmount(integration);

        //4、设置积分成长值信息
        orderEntity.setIntegration(integrationTotal);
        orderEntity.setGrowth(growthTotal);

        //5、设置删除状态(0-未删除，1-已删除)
        orderEntity.setDeleteStatus(0);

    }

    /**
     * 创建订单一系列操作：构建所有订单项数据：
     * */
    private List<OrderItemEntity> buildOrderItems(String orderSn){

        List<OrderItemEntity> itemEntities = new ArrayList<>();
        List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        if (currentUserCartItems !=null && currentUserCartItems.size()>0){
            itemEntities = currentUserCartItems.stream().map(cartItem -> {
                OrderItemEntity itemEntity = buildOrderItem(cartItem);

                itemEntity.setOrderSn(orderSn);

                return itemEntity;
            }).collect(Collectors.toList());
        }
        return itemEntities;
    }

    /**
     * 创建订单一系列操作：构建所有订单项数据：构建每一个订单项数据
     * */
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {

        OrderItemEntity itemEntity = new OrderItemEntity();

        //1、订单信息，订单号（上一步已完成）

        //2、商品的spu信息
        Long skuId = cartItem.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuBrandNameVo data = r.getData(new TypeReference<SpuBrandNameVo>() {
        });
        itemEntity.setSpuId(data.getId());
        itemEntity.setSpuBrand(data.getBrandName());
        itemEntity.setSpuName(data.getSpuName());
        itemEntity.setCategoryId(data.getCatalogId());

        //3、商品的sku信息
        itemEntity.setSkuId(cartItem.getSkuId());
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPic(cartItem.getImage());
        itemEntity.setSkuPrice(cartItem.getPrice());
        //使用StringUtils.collectionToDelimitedString将list集合转换为String
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(cartItem.getCount());
        //4、优惠信息（不做）

        //5、积分信息
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        itemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());

        //6、订单项阿价格信息
        itemEntity.setPromotionAmount(BigDecimal.ZERO);
        itemEntity.setCouponAmount(BigDecimal.ZERO);
        itemEntity.setIntegrationAmount(BigDecimal.ZERO);
        //未减去优惠等的原价
        BigDecimal origin = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        //当前订单项的实际金额
        BigDecimal realPrice = origin.subtract(itemEntity.getPromotionAmount()).
                subtract(itemEntity.getCouponAmount()).
                subtract(itemEntity.getIntegrationAmount());
        itemEntity.setRealAmount(realPrice);

        return itemEntity;
    }

    /**
     * 创建订单一系列操作：构建订单号
     * */
    private OrderEntity buildOrder(String orderSn) {
        MemberRespVo respVo = LoginUserInterceptor.loginUser.get();

        OrderEntity entity = new OrderEntity();
        entity.setOrderSn(orderSn);
        //获取收获地址信息
        OrderSubmitVo submitVo = submitThreadLocal.get();
        R fare = wmsFeignService.getFare(submitVo.getAddrId());
        FareVo fareResp= fare.getData(new TypeReference<FareVo>() {
        });

        //设置会员Id、名字
        entity.setMemberId(respVo.getId());
        entity.setMemberUsername(respVo.getUsername());

        //设置运费
        entity.setFreightAmount(fareResp.getFare());
        //设置收获人的信息
        entity.setReceiverCity(fareResp.getAddress().getCity());
        entity.setReceiverDetailAddress(fareResp.getAddress().getDetailAddress());
        entity.setReceiverName(fareResp.getAddress().getName());
        entity.setReceiverPhone(fareResp.getAddress().getPhone());
        entity.setReceiverPostCode(fareResp.getAddress().getPostCode());
        entity.setReceiverProvince(fareResp.getAddress().getProvince());
        entity.setReceiverRegion(fareResp.getAddress().getRegion());

        //设置订单状态的相关信息
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        entity.setAutoConfirmDay(7);

        return entity;
    }

    /**
     * 创建秒杀订单
     * */
    @Override
    public void createSeckill(SeckillOrderTo seckillOrder) {
        //TODO 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillOrder.getOrderSn());
        orderEntity.setMemberId(seckillOrder.getMemberId());
        BigDecimal multiply = seckillOrder.getSeckillPrice().multiply(new BigDecimal("" + seckillOrder.getNum()));
        orderEntity.setPayAmount(multiply);

        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        this.save(orderEntity);

        //TODO 保存订单项信息 ProductFeignService
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(seckillOrder.getOrderSn());
        orderItemEntity.setRealAmount(multiply);

        R r = productFeignService.getSpuInfoBySkuId(seckillOrder.getSkuId());
        SpuBrandNameVo data = r.getData(new TypeReference<SpuBrandNameVo>() {
        });
        orderItemEntity.setSpuBrand(data.getBrandName());

        orderItemEntity.setSkuQuantity(seckillOrder.getNum());

        orderItemService.save(orderItemEntity);

    }


}